﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;

namespace EasySL.Core
{
    public class Request
    {
        public Request()
        {
            this.MethodName = string.Empty;
            this.Parameters = new Dictionary<string, object>();
        }

        public string MethodName { get; set; }
        public Dictionary<string, object> Parameters { get; set; }
        public bool EnableCache { get; set; }

        public string Serialize()
        {
            this.ResetMethodName();
            return JavaScriptConvert.SerializeObject(this);
        }

        public void ResetMethodName()
        {
            var keys = this.Parameters.Keys.ToArray();
            this.MethodName = string.Format("{0}({1})", this.MethodName, string.Join(",", keys));
        }

        public void Deserialize(string jsonString, Dictionary<string, MethodInfo> methods)
        {
            JObject root = JObject.Parse(jsonString);
            this.MethodName = (root["MethodName"] as JValue).Value.ToString();

            if (!methods.ContainsKey(this.MethodName))
                throw new Exception("Cant find the service method as " + this.MethodName);

            MethodInfo method = methods[this.MethodName];
            foreach (ParameterInfo pi in method.GetParameters())
            {
                string value = root["Parameters"][pi.Name].ToString();
                object valueObject = JavaScriptConvert.DeserializeObject(value, pi.ParameterType);
                this.Parameters.Add(pi.Name, valueObject);
            }
        }

        public object[] GetParameterValues()
        {          
            if (this.Parameters == null)
                return null;

            List<object> values = new List<object>();

            foreach (object value in this.Parameters.Values)
                values.Add(value);

            return values.ToArray();
        }        
    }
}
